import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import '../index.dart';

class Api {
  // 在网络请求过程中可能会需要使用当前的context信息，比如在请求失败时
  late BuildContext context;

  Api(this.context);

  // 登录接口，登录成功后返回用户信息
  Future<ResponseData<User>> login(String account, String password) async {
    if (HttpGo.dio.options.headers["gxsaas-Auth"] != null) {
      //清理之前的缓存记录
      HttpGo.dio.options.headers.remove("gxsaas-Auth");
    }
    HttpGo httpGo = HttpGo(context);
    Response response = await HttpGo(context).post<User>(
      "/gxsaas-auth/token",
      data: {"account": account, "password": password, "grantType": "password"},
      options: httpGo.options.copyWith(headers: {
        HttpHeaders.authorizationHeader: 'Basic ' +
            base64.encode(
                utf8.encode('${HttpGo.clientId}:${HttpGo.clientSecret}'))
      }, extra: {
        "noCache": true, //本接口禁用缓存
      }),
      dataParseCallback: (data) => User.fromJson(data),
    );
    ResponseData<User> responseData = response.data;
    if (responseData.success) {
      //登录成功后更新公共头（authorization），此后的所有请求都会带上用户身份信息
      //清空所有缓存
      Global.netCache.cache.clear();
      //更新profile中的token信息
      Global.profile.token =
          'bearer ' + (responseData.dataModel?.accessToken ?? "");
      // 因为登录页返回后，首页会build，所以我们传false，更新user后不触发更新
      Provider.of<UserModel>(context, listen: false).user =
          responseData.dataModel;
    }
    return responseData;
  }

  //获取待办列表
  Future<ResponseData<RecordData<Todo>>> getListTodo(
      {int type = 0,
      required Map<String, dynamic> queryParameters, //query参数，用于接收分页信息
      refresh = false}) async {
    HttpGo httpGo = HttpGo(context);
    if (refresh) {
      // 列表下拉刷新，需要删除缓存（拦截器中会读取这些信息）
      httpGo.options.extra!.addAll({"refresh": true, "list": true});
    }
    String url;
    switch (type) {
      case 1:
        //已办
        url = "/gxsaas-flowable/app/v1/flowTask/listDone";
        break;
      case 2:
        //抄送
        url = "/gxsaas-flowable/app/v1/flowTask/listToCc";
        break;
      case 3:
        //提交
        url = "/gxsaas-flowable/app/v1/flowTask/listToSubmit";
        break;
      default:
        //待办
        url = "/gxsaas-flowable/app/v1/flowTask/listTodo";
    }

    Response response = await httpGo.get<RecordData<Todo>>(url,
        queryParameters: queryParameters,
        options: httpGo.options,
        dataParseCallback: (data) => RecordData<Todo>.fromJson(data,
            recordParseCallBack: (listData) =>
                listData.map<Todo>((e) => Todo.fromJson(e)).toList()));
    return response.data;
  }

  //获取工单列表
  Future<ResponseData<RecordData<Order>>> getOrderList(
      {required Map<String, dynamic> queryParameters, //query参数，用于接收分页信息
      refresh = false}) async {
    HttpGo httpGo = HttpGo(context);
    if (refresh) {
      // 列表下拉刷新，需要删除缓存（拦截器中会读取这些信息）
      httpGo.options.extra!.addAll({"refresh": true, "list": true});
    }
    Response response = await httpGo.get<RecordData<Order>>(
        "/gxsaas-produce/app/v1/order/list",
        queryParameters: queryParameters,
        options: httpGo.options,
        dataParseCallback: (data) => RecordData<Order>.fromJson(data,
            recordParseCallBack: (listData) =>
                listData.map<Order>((e) => Order.fromJson(e)).toList()));
    return response.data;
    // return ResponseData.fromJson(response.data, callDataParseBack: (data) {
    //   return RecordData<Order>.fromJson(data, callRecordParseBack: (listData) {
    //     return listData.map<Order>((e) => Order.fromJson(e)).toList();
    //   });
    // });
  }

  //获取工单详情
  Future<ResponseData<Order>> getOrder(
      {required Map<String, dynamic> queryParameters}) async {
    Response response = await HttpGo(context).get<Order>(
        "/gxsaas-produce/app/v1/order/view",
        queryParameters: queryParameters,
        dataParseCallback: (data) => Order.fromJson(data));
    return response.data;
  }

  //获取工单详情
  Future<ResponseData<Order>> addOrder(
      {required Map<String, dynamic> data}) async {
    HttpGo httpGo = HttpGo(context);
    Response response = await httpGo.post<Order>(
      "/gxsaas-produce/app/v1/order/add",
      data: data,
      options: httpGo.options.copyWith(headers: {
        HttpHeaders.contentTypeHeader: HttpGo.kContentTypeHeaderJson
      }),
      dataParseCallback: (data) => Order.fromJson(data),
    );
    return response.data;
  }

  //编辑工单
  Future<ResponseData> editOrder({required Map<String, dynamic> data}) async {
    HttpGo httpGo = HttpGo(context);
    Response response = await httpGo.post("/gxsaas-produce/app/v1/order/update",
        data: data,
        options: httpGo.options.copyWith(headers: {
          HttpHeaders.contentTypeHeader: HttpGo.kContentTypeHeaderJson
        }));
    return response.data;
  }

  //发送工单
  Future<ResponseData> sendOrder({required String orderId}) async {
    HttpGo httpGo = HttpGo(context);
    Response response = await httpGo.post(
        "/gxsaas-produce/app/v1/order/sendOrder",
        queryParameters: {"id": orderId},
        options: httpGo.options.copyWith(headers: {
          HttpHeaders.contentTypeHeader: HttpGo.kContentTypeHeaderJson
        }));
    return response.data;
  }

  //删除工单
  Future<ResponseData> deleteOrder({
    required String ids,
  }) async {
    Response response = await HttpGo(context).post(
      "/gxsaas-produce/app/v1/order/remove",
      queryParameters: {"ids": ids},
    );
    return response.data;
  }

  //回退工单
  Future<ResponseData> backOrder({
    required TaskRequest taskRequest,
  }) async {
    HttpGo httpGo = HttpGo(context);
    Response response = await httpGo.put(
        "/gxsaas-flowable/app/v1/flowTask/back",
        data: taskRequest.toJson(),
        options: httpGo.options.copyWith(headers: {
          HttpHeaders.contentTypeHeader: HttpGo.kContentTypeHeaderJson
        }));
    return response.data;
  }

//处理工单
  Future<ResponseData> handleOrder({
    required TaskRequest taskRequest,
  }) async {
    HttpGo httpGo = HttpGo(context);
    Response response = await httpGo.put(
        "/gxsaas-flowable/app/v1/flowTask/complete",
        data: taskRequest.toJson(),
        options: httpGo.options.copyWith(headers: {
          HttpHeaders.contentTypeHeader: HttpGo.kContentTypeHeaderJson
        }));
    return response.data;
  }

//获取操作日志
  Future<ResponseData<List<TaskLog>>> getTaskLogList({
    required String businessKey, //query参数，用于接收分页信息
  }) async {
    Response response = await HttpGo(context).get<List<TaskLog>>(
      "/gxsaas-flowable/app/v1/flowTask/getOperationLogByBusinessKey",
      queryParameters: {"businessKey": businessKey},
      dataParseCallback: (listData) =>
          listData.map<TaskLog>((e) => TaskLog.fromJson(e)).toList(),
    );
    return response.data;
  }

  // //获取首页
  // Future<ResponseData> getHome({
  //   Map<String, dynamic>? queryParameters, //query参数，用于接收分页信息
  // }) async {
  //   Response response = await dio.get(
  //     "/gxsaas-system/menu/routes",
  //     queryParameters: queryParameters,
  //   );
  //   return ResponseData.fromJson(response.data);
  // }

  //获取数据字典
  Future<ResponseData<List<Dict>>> getDictionary({
    Map<String, dynamic>? queryParameters, //query参数，用于接收分页信息
  }) async {
    Response response = await HttpGo(context).get<List<Dict>>(
      "/gxsaas-system/dict/list",
      queryParameters: queryParameters,
      dataParseCallback: (data) =>
          data.map<Dict>((e) => Dict.fromJson(e)).toList(),
    );
    return response.data;
  }

  //获取当前用户配置
  Future<ResponseData<UserConfigure>> getUserConfigure() async {
    Response response = await HttpGo(context).get<UserConfigure>(
      "/gxsaas-system/app/v1/getHomeSetting",
      dataParseCallback: (data) {
        if (data == null ||
            data["homeSetting"] == null ||
            (data["homeSetting"] as String).isEmpty) {
          return null;
        } else {
          return UserConfigure.fromJson(jsonDecode(data["homeSetting"]));
        }
      },
    );
    return response.data;
  }

  //修改当前用户配置
  Future<ResponseData> updateUserConfigure(
    UserConfigure userConfigure,
    //query参数，用于接收分页信息
  ) async {
    Response response = await HttpGo(context).post(
      "/gxsaas-system/app/v1/updateHomeSetting",
      queryParameters: {"homeSetting": jsonEncode(userConfigure.toJson())},
    );
    return response.data;
  }

  //获取首页数据
  Future<ResponseData<HomePageReport>> getHomePageReport() async {
    Response response = await HttpGo(context).get<HomePageReport>(
      "/gxsaas-system/app/v1/appHomePageReport",
      dataParseCallback: (data) => HomePageReport.fromJson(data),
    );
    return response.data;
  }

  //获取当前用户权限数据
  Future<ResponseData<List<Permission>>> getPermission({
    Map<String, dynamic>? queryParameters, //query参数，用于接收分页信息
  }) async {
    Response response = await HttpGo(context).get<List<Permission>>(
      "/gxsaas-system/app/v1/getAppMenuButtons",
      queryParameters: queryParameters,
      dataParseCallback: (data) =>
          data.map<Permission>((e) => Permission.fromJson(e)).toList(),
    );
    return response.data;
  }

  //获取组织机构
  Future<ResponseData<List<Dept>>> getDeptTree({
    Map<String, dynamic>? queryParameters, //query参数，用于接收分页信息
  }) async {
    Response response = await HttpGo(context).get<List<Dept>>(
      "/gxsaas-system/dept/getDeptTree",
      queryParameters: queryParameters,
      dataParseCallback: (data) =>
          data.map<Dept>((e) => Dept.fromJson(e)).toList(),
    );
    ResponseData<List<Dept>> responseData = response.data;
    return responseData;
  }

  //获取验证码
  Future<ResponseData> postLoginCode(String phone) async {
    Response response = await HttpGo(context)
        .post("/gxsaas-auth/loginValidationCode", data: {"phoneCode": phone});
    return response.data;
  }

  //校验验证码是否正确有效
  Future<ResponseData> postCheckLoginCode(
      String phone, String validationCode) async {
    Response response = await HttpGo(context).post(
        "/gxsaas-auth/checkValidationCode",
        data: {"phone": phone, "validationCode": validationCode});
    return response.data;
  }

  //校验验证码是否正确有效
  Future<ResponseData> postPasswordLoginCode(
      String phone, String newPassword) async {
    Response response = await HttpGo(context).post(
        "/gxsaas-system/user/update-password-by-validation-code",
        data: {"phone": phone, "newPassword": newPassword});
    return response.data;
  }

  //查询用户列表
  Future<ResponseData<List<UserInfo>>> getUserList({
    Map<String, dynamic>? queryParameters, //query参数，用于接收分页信息
  }) async {
    Response response = await HttpGo(context).get<List<UserInfo>>(
        "/gxsaas-system/user/tenant-user-list",
        queryParameters: queryParameters,
        dataParseCallback: (data) =>
            data.map<UserInfo>((e) => UserInfo.fromJson(e)).toList());
    return response.data;
  }

  //重置密码
  Future<ResponseData> postUpdatePassword(
      String oldPassword, String newPassword, String newPassword1) async {
    Response response = await HttpGo(context)
        .post("/gxsaas-system/user/update-password", data: {
      "oldPassword": oldPassword,
      "newPassword": newPassword,
      "newPassword1": newPassword1
    });
    return response.data;
  }

  //获取工单配置
  Future<ResponseData<List<OrderCfg>>> getAllOrderCfg({
    Map<String, dynamic>? queryParameters, //query参数，用于接收分页信息
  }) async {
    Response response = await HttpGo(context).get<List<OrderCfg>>(
      "/gxsaas-produce/app/v1/order/getAllOrderCfg",
      queryParameters: queryParameters,
      dataParseCallback: (data) =>
          data.map<OrderCfg>((e) => OrderCfg.fromJson(e)).toList(),
    );
    return response.data;
  }

  //查询任务办理数据
  Future<ResponseData<ExecuteTask>> getExecuteTaskData({
    String? taskId,
    String? businessKey,
  }) async {
    Map<String, dynamic>? queryParameters;
    if (businessKey != null) {
      queryParameters = {"businessKey": businessKey};
    } else if (taskId != null) {
      queryParameters = {"taskId": taskId};
    }
    Response response = await HttpGo(context).get<ExecuteTask>(
      "/gxsaas-flowable/app/v1/flowTask/executeTaskData",
      queryParameters: queryParameters,
      dataParseCallback: (data) => ExecuteTask.fromJson(data),
    );
    return response.data;
  }

  //上传文件
  Future<ResponseData<List<TyFile>>> uploadFile({
    required Map<String, dynamic> data, //query参数，用于接收分页信息
  }) async {
    FormData formData = FormData.fromMap(data);
    Response response = await HttpGo(context).post<List<TyFile>>(
      "/gxsaas-system/xfile/put-file",
      data: formData,
      dataParseCallback: (data) =>
          data.map<TyFile>((e) => TyFile.fromJson(e)).toList(),
    );
    return response.data;
  }
}
